package com.zhangtai.modules.controller.member;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhangtai.exception.RException;
import com.zhangtai.modules.constVo.BpmConst;
import com.zhangtai.modules.controller.admin.*;
import com.zhangtai.modules.controller.admin.JobController;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.controller.aouthLogin.MemberLoginController;
import com.zhangtai.modules.dao.*;
//import com.zhangtai.modules.dao.ssqlDao.BpmUserDao;
//import com.zhangtai.modules.dao.ssqlDao.SsqlSalaryGoupDao;
import com.zhangtai.modules.dto.LztkDto;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.employee.DimissionInfoEntity;
import com.zhangtai.modules.entity.employee.DimissionSettlementEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.flow.FlowEntity;
import com.zhangtai.modules.entity.leave.LeaveInfoEntity;
import com.zhangtai.modules.entity.system.BpmDataConfigurationEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.dimission.DimissionService;
import com.zhangtai.modules.service.employee.EmployeeBpmService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.flow.FlowService;
import com.zhangtai.modules.service.leave.LeaveInfoService;
import com.zhangtai.modules.service.promotion.PromotionService;
import com.zhangtai.modules.service.salary.AwardInfoService;
import com.zhangtai.modules.service.salary.SalaryBandService;
import com.zhangtai.modules.service.transfer.TransferInfoService;
import com.zhangtai.utils.EncryptUtil;
import com.zhangtai.utils.R;
import com.zhangtai.utils.SnowflakeIdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ming
 * @Date: 2020/6/2 0002 下午 8:17
 */
@RestController
@Slf4j
@RequestMapping("bpmMember")
@Api(tags = "审核接口BPM审核自助端")
public class BpmMemberController {
    @Value("${bpm.initiateUrl}")
    private String initiateUrl;
    private static final String bsid = "ZT_HRSYSTEM";
    private static final String dimissionBtid = "ZT_HR_DCJTLZSQ"; //离职申请集团
    private static final String dimissionBtidArea = "ZT_HR_DCQYLZSQ";//离职申请区域

    private static final String dimissionSettlementBtid = "ZT_HR_DCLZJS"; //离职结算

    private static final String key = "9d959e2640a74c4ebc9de0260c4e760c";

    @Autowired
    private EmployeeInfoService employeeInfoService;


    @Autowired
    private FlowService flowService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;


    @Autowired
    private DimissionInfoDao dimissionInfoDao;
    @Autowired
    private DimissionSettlementDao dimissionSettlementDao;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private MemberLoginController memberLoginController;

//
//    @Autowired
//    private BpmController bpmController;
//
//    @Autowired
//    private   SsqlSalaryGoupDao ssqlSalaryGoupDao;
//
//    @Autowired
//    private  BpmUserDao bpmUserDao;


//    @GetMapping("/dimissionApplyBpm")
//    @ApiOperation(value = "离职申请bpm发起接口")
//    public R<String> dimissionApplyBpm(@RequestParam("id") Long id,@RequestParam("oid") Long oid, HttpServletRequest request) throws Exception {
//
//        DimissionInfoEntity dimissionInfoEntity =  dimissionInfoDao.selectById(id);
//        if (ObjectUtils.isEmpty(dimissionInfoEntity)){
//            throw new RException("查询DimissionInfoEntity为空");
//        }
//        long flowId = snowflakeIdWorker.nextId();
//        FlowEntity flow = new FlowEntity();
//        flow.setFlowId(flowId);
//        //将审批状态修改为 2： 审批中
//        flow.setStatus(1);
//        //流程中各类 3 离职申请
//        flow.setFlowType(BpmConst.BPM_DIMISSION);
//        //员工id
//        flow.setOid(oid);
//        //关联记录id
//        flow.setRelateId(id);
//
//        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
//
//        String applyUserCode = userInfo.getString("usercode");
//      // String applyUserCode = "test";
////        String username = userInfo.getString("user_name");
//     //  String username = "test";
//
//        if (StringUtils.isEmpty(applyUserCode)) {
//            throw new RException("请先登录");
//        }
//        //        根据工号查询所在机构代码
//       // String orgCodeByUserCode = bpmUserDao.findOrgIdByUserCode(applyUserCode);
//        String orgCodeByUserCode="";
//        String str = bsid + "|" + applyUserCode + "|" + System.currentTimeMillis();
//
////        boolean isGroup=bpmController.isGroup(userInfo.getLong("orgId"));
////        String btid=dimissionBtidArea;
////        if(isGroup){
////            btid = dimissionBtid;
////        }
//        EmployeeInfoEntity entity=employeeInfoService.getByIdE(oid);
//        if(ObjectUtils.isEmpty(entity.getJobSystemId())){
//            return  R.error("该员工未分配体系");
//        }
//        BpmDataConfigurationEntity bpmDataConfigurationEntity= new BpmDataConfigurationEntity();
////                bpmController.getBtid(entity.getJobSystemId(),BpmConst.BPM_DIMISSION_TYPE);
//        String btid=bpmDataConfigurationEntity.getBpmtypeId();
//        if(StringUtils.isEmpty(btid)){
//            return R.error("该员工所在体系未配置该业务类型的BPM流程参数配置");
//        }
//        String signature = EncryptUtil.aesEncrypt(str, key);
//        String url = initiateUrl + "?bsid=" + bsid + "&btid=" + btid + "&boid=" + flowId + "&userid=" + applyUserCode + "&orgcode="+orgCodeByUserCode + "&signature=" + signature;
//        String secondUrl = "http://bpm.zhangtai.com.cn/Workflow/MTStart2.aspx?BSID=ZT_HRSYSTEM&BTID=" + btid + "&BOID=" + flowId + "&UserID=" + applyUserCode + "&signature=" + signature + "&IsCheckDataVersion=0";
//        HttpHeaders httpHeaders = new HttpHeaders();
//        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("businessObjectId", btid);
//        jsonObject.put("businessObjectName", "离职申请");
//        jsonObject.put("businessObjectUrl", "");
//        jsonObject.put("businessObjectModifyUrl", "");
//        jsonObject.put("businessObjectVersion", "");
//        EmployeeInfoEntity employeeInfoEntity=employeeInfoService.getByIdE(dimissionInfoEntity.getOid());
//     //  JSONArray array = bpmController.getDimissionInfoParam(dimissionInfoEntity, employeeInfoEntity);
//        JSONArray array = bpmController.getDimissionInfoParamArea(dimissionInfoEntity, employeeInfoEntity);
//        if ("1".equals(bpmDataConfigurationEntity.getIsGroupId())) {
//            array = bpmController.getDimissionInfoParam(dimissionInfoEntity, employeeInfoEntity);
//        }
//
//        jsonObject.put("fields", array);
//        //   封装附件
//       // List<ImgUrlEntity> imgUrlEntities = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", id).eq("type", 8).eq("is_delete", 0));
//
//        jsonObject = bpmController.getAttachmentsByUrl(jsonObject, dimissionInfoEntity.getUrlIds());
//        JSONObject object = new JSONObject();
//        object.put("businessObject", jsonObject);
//
//        log.info("离职申请请求参数是：{}", object);
//
//        HttpEntity<String> httpEntity = new HttpEntity<>(object.toJSONString(), httpHeaders);
//        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
//        JSONObject body = responseEntity.getBody();
//        log.info("离职申请返回是:{}", body);
//        flowService.saveE(flow);
//
//        log.info("secondUrl:{}",secondUrl);
//        return R.ok(secondUrl);


//    }


//    @GetMapping("/dimissionSettlementBpm")
//    @ApiOperation(value = "离职结算bpm发起接口")
//    public R<String> dimissionSettlementBpm(@RequestParam("id") Long id, HttpServletRequest request) throws Exception {
//
//        //  结算发起申请 传明源的字段
////        List<LztkDto> mygts = ssqlSalaryGoupDao.getMygt();
//
//
//        DimissionSettlementEntity dimissionSettlementEntity =  dimissionSettlementDao.selectById(id);
//        if (ObjectUtils.isEmpty(dimissionSettlementEntity)){
//            throw new RException("查询DimissionSettlementEntity为空");
//        }
//        DimissionInfoEntity dimissionInfoEntity =  dimissionInfoDao.selectById(dimissionSettlementEntity.getDimissionId());
//        //  结算发起申请 传明源的字段
////        List<LztkDto> mygts = ssqlSalaryGoupDao.getMygt(dimissionInfoEntity.getApplyCode());
//        long flowId = snowflakeIdWorker.nextId();
//        FlowEntity flow = new FlowEntity();
//        flow.setFlowId(flowId);
//        //将审批状态修改为 2： 审批中
//        flow.setStatus(1);
//        //流程中各类 5 离职结算
//        flow.setFlowType(BpmConst.BPM_DIMISSION_SET);
//        //员工id
//        flow.setOid(dimissionInfoEntity.getOid());
//        //关联记录id
//        flow.setRelateId(id);
//
//        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
//
//        String applyUserCode = userInfo.getString("usercode");
//
//        long orgId = userInfo.getLong("orgId");
//        if (StringUtils.isEmpty(applyUserCode)) {
//            throw new RException("请先登录");
//        }
//        //        根据工号查询所在机构代码
//        String orgCodeByUserCode = bpmUserDao.findOrgIdByUserCode(applyUserCode);
//         orgCodeByUserCode="";
//        String str = bsid + "|" + applyUserCode + "|" + System.currentTimeMillis();
//
//        EmployeeInfoEntity entity=employeeInfoService.getByIdE(dimissionInfoEntity.getOid());
//        if(ObjectUtils.isEmpty(entity.getJobSystemId())){
//            return  R.error("该员工未分配体系");
//        }
//        BpmDataConfigurationEntity bpmDataConfigurationEntity=bpmController.getBtid(entity.getJobSystemId(),BpmConst.BPM_DIMISSION_SET_TYPE);
//        String btid=bpmDataConfigurationEntity.getBpmtypeId();
//        if(StringUtils.isEmpty(btid)){
//            return R.error("该员工所在体系未配置该业务类型的BPM流程参数配置");
//        }
//        String signature = EncryptUtil.aesEncrypt(str, key);
//        String url = initiateUrl + "?bsid=" + bsid + "&btid=" + btid + "&boid=" + flowId + "&userid=" + applyUserCode + "&orgcode=" + orgCodeByUserCode + "&signature=" + signature;
//        String secondUrl = "http://bpm.zhangtai.com.cn/Workflow/MTStart2.aspx?BSID=ZT_HRSYSTEM&BTID=" + btid + "&BOID=" + flowId + "&userid=" + applyUserCode +"&orgcode=" + orgCodeByUserCode+ "&signature=" + signature + "&IsCheckDataVersion=0";
//        HttpHeaders httpHeaders = new HttpHeaders();
//        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("businessObjectId", btid);
//        jsonObject.put("businessObjectName", "离职结算");
//        jsonObject.put("businessObjectUrl", "");
//        jsonObject.put("businessObjectModifyUrl", "");
//        jsonObject.put("businessObjectVersion", "");
//        EmployeeInfoEntity employeeInfoEntity=employeeInfoService.getByIdE(dimissionInfoEntity.getOid());
//        JSONArray array = bpmController.getDimissionSettlement(dimissionSettlementEntity,dimissionInfoEntity,employeeInfoEntity,orgId);
//
//
//
//
//        jsonObject.put("fields", array);
//
//
//
//
////        JSONArray mygtArray=new JSONArray();
////        JSONObject  mygtArrayObj= new JSONObject();
////        mygtArrayObj.put("listId","ZT_HR_DCLZJS_Gtdtl");
////        mygtArrayObj.put("listName","明源系统申请子表");
////        JSONArray myxt=new JSONArray();
////        for(LztkDto mygt:mygts){
////
////            JSONArray  arrayinfo = getMyGt(mygt);
////            myxt.add(arrayinfo);
////        }
////        mygtArrayObj.put("items",myxt);
////        mygtArray.add(mygtArrayObj);
////        jsonObject.put("lists", mygtArray);
//
//
//
//
//        //   封装附件
//        //List<ImgUrlEntity> imgUrlEntities = imgUrlDao.selectList(new QueryWrapper<ImgUrlEntity>().eq("oid", id).eq("type", 8).eq("is_delete", 0));
//
//        jsonObject = bpmController.getAttachmentsByUrl(jsonObject, dimissionSettlementEntity.getAnnexUrl());
//
//        JSONObject object = new JSONObject();
//        object.put("businessObject", jsonObject);
//
//        log.info("离职结算请求参数是：{}", object);
//
//        HttpEntity<String> httpEntity = new HttpEntity<>(object.toJSONString(), httpHeaders);
//        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
//        JSONObject body = responseEntity.getBody();
//        log.info("离职结算返回是:{}", body);
//        flowService.saveE(flow);
//        return R.ok(secondUrl);
//
//
//    }

    private JSONArray getMyGt(LztkDto mygt) {
        JSONArray jsonArray = new JSONArray();

        JSONObject jsonObj1 = new JSONObject();
        jsonObj1.put("id", "FaPackName");
        jsonObj1.put("value", mygt.getFaPackName());
        jsonArray.add(jsonObj1);

        JSONObject jsonObj2 = new JSONObject();
        jsonObj2.put("id", "UserName");
        jsonObj2.put("value", mygt.getUserName());
        jsonArray.add(jsonObj2);

        JSONObject jsonObj3 = new JSONObject();
        jsonObj3.put("id", "WorkNo");
        jsonObj3.put("value", mygt.getWorkNo());
        jsonArray.add(jsonObj3);

        JSONObject jsonObj4 = new JSONObject();
        jsonObj4.put("id", "PayPrincipal");
        jsonObj4.put("value",mygt.getPayPrincipal());
        jsonArray.add(jsonObj4);

        JSONObject jsonObj5 = new JSONObject();
        jsonObj5.put("id", "Syje");
        jsonObj5.put("value", mygt.getSyje());
        jsonArray.add(jsonObj5);

        JSONObject jsonObj6 = new JSONObject();
        jsonObj6.put("id", "FactReturnAmount");
        jsonObj6.put("value", mygt.getFactReturnAmount());
        jsonArray.add(jsonObj6);

        return  jsonArray;
    }


}
